import { useState, useCallback, useMemo, useEffect, forwardRef, useImperativeHandle } from 'react';
import { Button, Tooltip, notification } from 'antd';
import { Grid, Header } from 'gantd';
import { setPrompt, showActionText } from '@/utils/utils';
import SearchForm from '@/components/searchform';
import _ from 'lodash';
import { confirmUtil, commonText, showValidate, generateUuid } from '@/utils/utils';
import { useGrid } from '@/utils/hooks';
import { getCurrentUser } from '@/utils/user';
import { tableSchema, searchSchema } from './schema';
import { findPageRecipientListApi, batchSaveApi } from './service';
import { getRecipientList, getBomRom } from './util';

function RecipientList({ readOnly }, ref) {
  const { onGridReady, gridManagerRef, gridApiRef: apiRef } = useGrid(); //SmartGrid渲染完成之后的回调方法
  const [dataSource, setDataSource] = useState([]);
  const [loading, setLoading] = useState(false);
  const [editable, setEditable] = useState<boolean>(false); //动态编辑状态
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]); //table表格的多选框的id
  const [selectedRows, setSelectedRows] = useState<any[]>([]);

  // 获取列表数据
  const getList = useCallback(async (newFilterInfo: any = {}) => {
    const params = {
      filterInfo: { ...newFilterInfo },
      pageInfo: { beginIndex: 0, pageSize: 1500 },
    };
    setLoading(true);
    try {
      const res = await findPageRecipientListApi(params);
      setDataSource(res?.content);
    } catch (error) {}
    setLoading(false);
  }, []);

  // 搜素查询
  const onSearch = useCallback(
    (args) => {
      if (gridManagerRef.current?.isChanged) {
        confirmUtil({
          content: commonText.doSearchOnChangedText,
          onOk: () => {
            setSelectedRowKeys([]);
            getList(getBomRom(args));
          },
        });
      } else {
        setSelectedRowKeys([]);
        getList(getBomRom(args));
      }
    },
    [getList, gridManagerRef],
  );

  // 添加
  const onAdd = useCallback(() => {
    const id = `N_${generateUuid(6)}`;
    const newRow = {
      id,
    };
    gridManagerRef.current?.create({ ...newRow }, true);
  }, [gridManagerRef]);

  // 删除
  const onDelete = useCallback(() => {
    const selected = apiRef.current?.getSelectedNodes();
    if (selected.length > 0) {
      selected.forEach((item) => {
        if (item.id < 0) {
          gridManagerRef.current?.remove(item.id);
        } else {
          gridManagerRef.current?.tagRemove(item.id);
        }
      });
    } else {
      notification.warning({
        message: '请选择要删除的节点',
      });
    }
  }, [gridManagerRef, apiRef]);

  // 编辑按钮操作项
  const getContextMenuItems = useCallback(
    (params: any) => {
      const {
        context: { editable, onBatchSave, cancelEdit, onAdd },
      } = params;

      if (editable) {
        return [
          {
            name: '结束编辑',
            action: () => cancelEdit(),
          },
          {
            name: '新增',
            action: () => onAdd(dataSource),
          },
          {
            name: '删除',
            action: () => onDelete(dataSource),
          },
          {
            name: '撤销',
            action: () => gridManagerRef.current?.undo(),
          },
          {
            name: '保存',
            action: () => onBatchSave('save'),
          },
        ];
      }
      return [
        {
          name: '进入编辑',
          disabled: editable,
          action: () => {
            setEditable(true);
          },
        },
      ];
    },
    [gridManagerRef, dataSource, onDelete],
  );

  // 取消编辑
  const cancelEditData = useCallback(() => {
    const cancel = () => {
      gridManagerRef.current?.cancel();
      setEditable(false);
    };
    if (gridManagerRef.current?.isChanged) {
      confirmUtil({
        content: commonText.doCancelOnChangedText,
        onOk: cancel,
      });
    } else {
      cancel();
    }
  }, [gridManagerRef]);

  // 编辑保存
  const onBatchSaveData = useCallback(() => {
    gridManagerRef.current.onDataAsyncEnd(async () => {
      const { diff, validate } = gridManagerRef.current;
      if (!gridManagerRef.current.isChanged) {
        showActionText();
        return;
      }
      const valids = await validate();
      showValidate(valids);
      if (valids) {
        return;
      }
      const resolvedData = _.cloneDeep(diff);
      const { add, modify, remove } = resolvedData;
      await batchSaveApi({
        addedData: add.map((item) => ({
          ...item,
          recipientList: getRecipientList(item?.recipientList),
          userId: getCurrentUser()?.id,
        })),
        modifiedData: modify.map((item) => ({
          ...item,
          recipientList: getRecipientList(item?.recipientList),
          userId: getCurrentUser()?.id,
        })),
        removedData: remove,
      });
      getList();
    });
  }, [gridManagerRef, getList]);

  // 编辑状态的样式
  const headerRight = useMemo(() => {
    return (
      <>
        {editable ? (
          <>
            <Tooltip title={'新增'}>
              <Button size="small" icon="plus" onClick={() => onAdd()} />
            </Tooltip>
            <Tooltip title={'结束编辑'}>
              <Button size="small" icon="poweroff" onClick={() => cancelEditData()} />
            </Tooltip>
            <Tooltip title={'删除'}>
              <Button size="small" icon="minus" onClick={() => onDelete()} />
            </Tooltip>
            <Tooltip title={'撤销'}>
              <Button size="small" icon="redo" onClick={() => gridManagerRef.current?.undo()} />
            </Tooltip>
            <Tooltip title={'保存'}>
              <Button size="small" icon="save" onClick={() => onBatchSaveData('save')} />
            </Tooltip>
          </>
        ) : (
          <Tooltip title={'进入编辑'}>
            <Button
              onClick={() => {
                setEditable(true);
              }}
              size="small"
              icon="edit"
            />
          </Tooltip>
        )}
      </>
    );
  }, [setEditable, editable, cancelEditData, onBatchSaveData, gridManagerRef, onAdd, onDelete]);

  useImperativeHandle(
    ref,
    () => ({
      // 是否保存过预览信息 - 无子节点数据则代表没有保存
      getSelectRow: () => {
        return selectedRows;
      },
    }),
    [selectedRows],
  );

  useEffect(() => {
    getList();
  }, []);

  return (
    <>
      <SearchForm
        title="收件人列表"
        searchKey={`XbomDetailModal_RecipientList_${getCurrentUser()?.id}`}
        onSearch={onSearch}
        onValueChange={() => {}}
        schema={searchSchema}
        isCompatibilityMode
        onSizeChange={() => {}}
        headerProps={{
          type: 'line',
        }}
      />
      <Header type="line" title="" extra={!readOnly && headerRight} />
      <Grid
        rowkey={(data: any) => `XbomDetailModal_RecipientList_${data.id}`}
        gridKey={`XbomDetailModal_RecipientList_${getCurrentUser()?.id}`}
        height={300}
        loading={loading}
        columns={tableSchema}
        dataSource={dataSource}
        editable={editable}
        onReady={onGridReady}
        serialNumber
        openEditSign
        groupDefaultExpanded={-1}
        groupSuppressAutoColumn
        rowBuffer={100}
        rowSelection={{
          type: 'single',
          onSelect: (rowKeys: string[], rows: any[]) => {
            setSelectedRowKeys(rowKeys);
            setSelectedRows(rows);
          },
          selectedRows,
          selectedKeys: selectedRowKeys,
        }}
        style={{ padding: '0 3px' }}
        getContextMenuItems={getContextMenuItems}
        editChangeCallback={(isChange) => {
          setPrompt(isChange);
        }}
      />
    </>
  );
}

export default forwardRef(RecipientList);
